package com.superbit.web.servlet;

import java.math.BigDecimal;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;

import com.superbit.core.constant.QuoteOrderConstant;
import com.superbit.core.exception.BusinessException;
import com.superbit.core.exception.ParamInvalidException;
import com.superbit.core.service.QuoteOrderService;
import com.superbit.core.tools.PageListRes;
import com.superbit.core.vo.QuoteOrderVO;
import com.superbit.web.excep.NoLoginException;
import com.superbit.web.listener.ServiceBeanFactory;
import com.superbit.web.utils.JsonResponseUtil;
import com.superbit.web.utils.PageInfoObjct;
import com.superbit.web.utils.StringPropertiesUtil;
import com.superbit.web.utils.StringValidateUtil;


/**
 * 报价相关controller层
 * @author 赵世栋
 * @version
 *  2018-01-08
 *
 */

@Controller
@RequestMapping("/quoteorder.act")
public class QuoteOrderController {
	
	private QuoteOrderService quoteOrderService;
	
	private String uri = "/quoteorade.act";
	
	@PostConstruct
	private void init(){
		quoteOrderService = ServiceBeanFactory.getBean(QuoteOrderService.class);
	}
	
	/**
	 * 获取大盘深度信息
	 * @param session
	 * @param coinCode  币种类型
	 * @param sortName  排序名称
	 * @param sortType  排序方式 
	 * @return
	 */
	@RequestMapping(params = "cmd=getDefaultDeepenDatas")
	@ResponseBody
	public String getGrailDeepenDatas(HttpSession session,String coinCode,String dataSize){
		if(StringUtils.isEmpty(coinCode)){
			return JsonResponseUtil.buildNormalExcepResonpe(QuoteOrderConstant.PARAMISINVALID, "param can not be null").toString();
		}
		if(StringUtils.isEmpty(dataSize)){
			dataSize="100";
		}
		Integer size = StringValidateUtil.strToInt(dataSize, "dataSize");
		Map<String, Object> grailData = this.quoteOrderService.getGrailData(coinCode,size);
		return JsonResponseUtil.buildSucessResonpe(grailData).toString();
	}
	/**
	 * 获取更多报价信息     默认前100条
	 * @param session
	 * @param showType 1:卖出 \0:买入   
	 * @param coinCode   对应的币种码
	 * @param size 数据量（默认为100）
	 * @return
	 */
	@RequestMapping( params = "cmd=getMoreOrderList")
	@ResponseBody
	public String getMoreQuoteOrderList(HttpSession session,String showType,String coinCode ,String size,String sortName,String sortType){
		if(StringUtils.isEmpty(showType)||StringUtils.isEmpty(coinCode)){
			throw new ParamInvalidException("showType || coinId ", "param can not be null");
		}
//		Integer showtype = StringValidateUtil.strToInt(showType, "showType");
//		Map<String, Object> map = this.quoteOrderService.getMoreQuoteOrderList(showtype, coinCode, sortName, sortType,size);
		
		//TODO 统一返回格式 
		return null;
	}
	
	
	
	/**
	 * 下买入报价单
	 * @param session 
	 * @param priceCNY          订单价格(单价)
	 * @param indexPrice        指数价
	 * @param amountCoin        数量
	 * @param totalPrice  		报价单总价
	 * @param ALOtransaction    最小交易量
	 * @param payType           支付方式 
	 * @param coinCode            币种码
	 * @param sellerUserId      卖家userId
	 * @param quoteId           报价Id                     N
	 * @param isAutoSetting     设置 0：未勾选 1：勾选                N
	 * @param setValue 			设置值                                           N
	 * @return
	 */
	@RequestMapping(params = "cmd=placeBuyQuoteOrder")
	@ResponseBody
	public String placeBuyQuoteOrder(HttpSession session,String indexPrice,String priceCNY,String amountCoin, String totalPrice,String  ALOtransaction, String payType,
			String coinCode, String sellerUserId,String quoteId, String isAutoSetting, String setValue){
			boolean result=false;
			Integer userId = StringPropertiesUtil.getUserId(session);
			if(userId == null){
				throw new NoLoginException(uri,"cmd=placeBuyQuoteOrder");
			}
			if(StringUtils.isEmpty(ALOtransaction)||StringUtils.isEmpty(coinCode) ||StringUtils.isEmpty(priceCNY)|| StringUtils.isEmpty(totalPrice)){
				
				throw new ParamInvalidException("ALOtransaction|| coinCode || priceCNY || totalPrice", "is null");
			}
			// 价格精确度 （法币）
			if(checkPriceNoAvailable(priceCNY,false)||checkPriceNoAvailable(totalPrice,false)|| checkPriceNoAvailable(indexPrice,false)||checkPriceNoAvailable(ALOtransaction,false)){
				throw new ParamInvalidException("priceCNY ", "two bits after a decimal point");
			}
			//币数精确度（数字币）
			if(checkPriceNoAvailable(amountCoin,true)){
				throw new ParamInvalidException("amount", "eight bits after a decimal point");
			}
			//最小交易必须小于总价
			if(checkTotalPrice(ALOtransaction,totalPrice)){
				throw new ParamInvalidException("ALO", "is outside the law");
			}
			if(StringUtils.isEmpty(payType)){
				throw new ParamInvalidException("payType", "choose pay method");
			}
			
			double price = StringValidateUtil.strToDouble(priceCNY, "priceCNY");
			double amount = StringValidateUtil.strToDouble(amountCoin, "amountCoin");
			double total = StringValidateUtil.strToDouble(totalPrice, "totalPrice");
			Integer ALO = StringValidateUtil.strToInt(ALOtransaction, "ALOtransaction");
			long quoteOrderId = 0;
			if(!StringUtils.isEmpty(quoteId)){
			 quoteOrderId = StringValidateUtil.strToLong(quoteId,"quoteId");
			}
			Integer isAutoSet= StringValidateUtil.strToInt(isAutoSetting, "isAutoSetting");
			
			if(price < 0){
				throw new ParamInvalidException("priceCNY", "不能小于零");
			}
			if(amount < 0){
				throw new ParamInvalidException("amountCoin", "不能小于零");
			}
			if(total < 0){
				throw new ParamInvalidException("totalPrice", "不能小于零");
			}
			try{
			result = this.quoteOrderService.buyinQuoteOrder(new BigDecimal(indexPrice),price,new BigDecimal(amount),new BigDecimal(total),ALO,payType,coinCode,userId,sellerUserId,quoteOrderId,isAutoSet,setValue);
			//TODO 过滤参数
			}catch(BusinessException e){
				return JsonResponseUtil.buildBusiExcepResonpe(e).toString();
			}
		return JsonResponseUtil.buildSucessResonpe(result).toString();
		
	}
	/**
	 * 下买入报价单
	 * @param session 
	 * @param priceCNY          订单价格(单价)
	 * @param amountCoin        数量
	 * @param totalPrice  		报价单总价
	 * @param ALOtransaction    最小交易量
	 * @param payType           支付方式 
	 * @param coinCode           币种码
	 * @param buyserUserId      买家userId
	 * @param quoteId           报价Id
	 * @param isAutoSetting     设置 0：未勾选 1：勾选
	 * @param setValue 			设置值
	 * @return
	 */
	@RequestMapping(params = "cmd=placeSellQuoteOrder")
	@ResponseBody
	public String placeSellQuoteOrder(HttpSession session,String indexPrice,String priceCNY,String amountCoin, String totalPrice,String  ALOtransaction, String payType,
			String coinCode, String buyserUserId,String quoteId, String isAutoSetting, String setValue){
		boolean result=false;
		Integer userId = StringPropertiesUtil.getUserId(session);
		if(userId == null){
			throw new NoLoginException(uri,"cmd=placeBuyQuoteOrder");
		}
		if(StringUtils.isEmpty(ALOtransaction)||StringUtils.isEmpty(coinCode) ||StringUtils.isEmpty(priceCNY)|| StringUtils.isEmpty(totalPrice)){
			
			throw new ParamInvalidException("ALOtransaction|| coinCode || priceCNY || totalPrice", "is null");
		}
		// 价格精确度 （法币）
		if(checkPriceNoAvailable(priceCNY,false)||checkPriceNoAvailable(totalPrice,false)|| checkPriceNoAvailable(indexPrice,false)||checkPriceNoAvailable(ALOtransaction,false)){
			throw new ParamInvalidException("priceCNY ", "two bits after a decimal point");
		}
		//币数精确度（数字币）
		if(checkPriceNoAvailable(amountCoin,true)){
			throw new ParamInvalidException("amount", "eight bits after a decimal point");
		}
		//最小交易必须小于总价
		if(checkTotalPrice(ALOtransaction,totalPrice)){
			throw new ParamInvalidException("ALO", "is outside the law");
		}
		if(StringUtils.isEmpty(payType)){
			throw new ParamInvalidException("payType", "choose pay method");
		}
		
		double price = StringValidateUtil.strToDouble(priceCNY, "priceCNY");
		double amount = StringValidateUtil.strToDouble(amountCoin, "amountCoin");
		double total = StringValidateUtil.strToDouble(totalPrice, "totalPrice");
		Integer ALO = StringValidateUtil.strToInt(ALOtransaction, "ALOtransaction");
		long quoteOrderId = 0;
		if(!StringUtils.isEmpty(quoteId)){
		 quoteOrderId = StringValidateUtil.strToLong(quoteId,"quoteId");
		}
		Integer isAutoSet= StringValidateUtil.strToInt(isAutoSetting, "isAutoSetting");
		
		if(price < 0){
			throw new ParamInvalidException("priceCNY", "不能小于零");
		}
		if(amount < 0){
			throw new ParamInvalidException("amountCoin", "不能小于零");
		}
		if(total < 0){
			throw new ParamInvalidException("totalPrice", "不能小于零");
		}
		try{
		result = this.quoteOrderService.selloutQuoteOrder(new BigDecimal(indexPrice),price, new BigDecimal(amount), new BigDecimal(total), ALO, payType, coinCode, buyserUserId, userId, quoteOrderId,isAutoSet,setValue);
		}catch(BusinessException e){
			return JsonResponseUtil.buildBusiExcepResonpe(e).toString();
		}
	return JsonResponseUtil.buildSucessResonpe(result).toString();
		
	}
	/**
	 * 撤销报价订单
	 * @param session
	 * @param quoteStatus  报价状态
	 * @param quoteId	   报价id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(params = "cmd=canceQuotelOrder")
	public String cancelQuoteOrder(HttpSession session,String quoteStatus,String quoteId ){
		Integer userId = StringPropertiesUtil.getUserId(session);
		if(userId == null){
			throw new NoLoginException(uri,"cancelQuoteOrder");
		}
		if(StringUtils.isEmpty(quoteStatus) || StringUtils.isEmpty(quoteId)){
			throw new ParamInvalidException("quoteStatus or quoteId ", "param is null");
		}
		Integer quoteOrderId = StringValidateUtil.strToInt(quoteId, "quoteId");
		Integer quoteOrderStatus = StringValidateUtil.strToInt(quoteStatus,"quoteStatus");
	  try {
		  boolean  result = this.quoteOrderService.cancelQuoteOrder(quoteOrderId, quoteOrderStatus,userId);
		return JsonResponseUtil.buildSucessResonpe(result).toString();
		} catch (BusinessException e) {
			
			return JsonResponseUtil.buildNormalExcepResonpe("QU005", "cancel failling please delete later ").toString();
		}
	}
	
	/**
	 * 获取报价列表
	 * @param session
	 * @param queryStr 查询字段 all :全部   buy： 买入  sell：卖出
	 * @param pageNumber
	 * @param pageSize
	 * @param coinCode 币种码
	 * @date 2018-01-15 已测试
	 * @return
	 */
	@RequestMapping( params = "cmd=getQuoteOrderList" )
	@ResponseBody
	public String getQuoteOrderList(HttpServletRequest req,String queryStr,String pageNumber,String pageSize,String coinCode){
		Integer userId = StringPropertiesUtil.getUserId(req.getSession());
		if(userId == null){
			throw new NoLoginException(uri,"getQuoteOrderList");
		}

		if(StringUtils.isEmpty(queryStr)){
			throw new ParamInvalidException("queryStr", "param is null");
		}
		PageInfoObjct pageinfo = PageInfoObjct.getPageInfo(pageNumber, pageSize);
		PageListRes<QuoteOrderVO> list = this.quoteOrderService.getQuoteOrderList(1,coinCode, queryStr, pageinfo.getCurrentpage(), pageinfo.getSizeperpage());
		return JsonResponseUtil.buildSucessResonpe(list).toString();

	}
	/**
	 * 检查价格参数是否符合规范   
	 * @describle :统一设置为保留小数点八位小数
	 * @param str  待处理数据
	 * @param isCoin 是否是数字币
	 * @return true:不可以   false ：参数可用
	 */
	private boolean checkPriceNoAvailable(String str ,boolean isCoin){
		boolean flag = false;
		boolean isContains = str.contains(".");
		if(isContains){
		String[] split = str.split("\\.");
		if(isCoin){
			//是数字币
			if(split[1].length() > QuoteOrderConstant.QUOTE_COIN_ACCURY){
				flag = true;
			}
		}else{
			//是法币
			if(split[1].length() > QuoteOrderConstant.QUOTE_CNY_ACCURAY){
				flag = true;
			}
		}
		
	}
		return flag;
	}
	/**
	 * 检查最小交易额  和总价的大小
	 * @param ALO
	 * @param totalPrice
	 * @return true :合法  false :不合法
	 */
	private boolean checkTotalPrice(String ALO,String totalPrice){
		boolean flag =true;
		BigDecimal alo = new BigDecimal(ALO);
		BigDecimal total = new BigDecimal(totalPrice);
		if(alo.compareTo(total) == 1){
			flag =false;
		}
		return flag;
	}
}
